//
//  RootViewController.m
//  网络连接之天气预报
//
//  Created by My Mac on 2017/3/17.
//  Copyright © 2017年 My Mac. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()
@property(nonatomic,strong) UILabel *dateLabel;
@property(nonatomic,strong) UILabel *weekLabel;
@property(nonatomic,strong) UILabel *cityLabel;
@property(nonatomic,strong) UILabel *temperatureLabel;

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"天气预报";
    [self initViews];
    [self loadData];
    
}
-(void)initViews {
    
}
-(void)loadData {
    /*
     * 访问网络：在info.plist文件中,添加App Transport Security Settings 行,
     * 并再添加子项(键值对) Allow Arbitrary Loads,将其值设置为YES
     */
    NSString *city = @"株洲";
    NSString *address = [NSString stringWithFormat:@"http://v.juhe.cn/weather/index?format=1&cityname=%@&key=e2f6a4092df0c4297cace23b69e6708e",city];
    /*
     * 注意对于url中的中文是无法解析的，需要进行url编码(指定编码类型为utf-8)
     * url解码使用stringByRemovingPercentEncoding方法
     */
    address = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //拼接网络地址（url）
    NSURL *url = [NSURL URLWithString:address];
    
    //网络请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSLog(@"%@",request);
    
    //网络会话
    NSURLSession *session = [NSURLSession sharedSession];
    NSLog(@"%@",session);
    
    //创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //接收数据
        NSString *dataContent = [[NSString alloc]initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
        NSLog(@"%@",dataContent);
        //将数据转成字典
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"%@",dict);
        //之后可以调用主线程更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
           //在这里面更新UI
            [self updateViews];
        });
    }];
    //执行任务
    [task resume];
    
}

-(void)updateViews{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
